import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import DatePicker from '../../../component/DatePicker';
import { SelectCpt } from './_components/SelectCpt';
import { TextareaCpt } from './_components/TextareaCpt';
import { AttachmentCpt } from './_components/AttachmentCpt';
import { EditMailCpt } from './_components/EditMailCpt';
import Utils from '../../../utils/utils';
import ToastUtil from '../../../utils/toast';
import APIService from './_common/APIService';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import moment from 'moment';

const scale = GLOBAL.SCALE;

// 发送时间
const SENDDATA = [
	{ dictKey: 1, dictName: "立即发送" },
	{ dictKey: 2, dictName: "等候发送" },
]


export class PushEail extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '邮件推送',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('StockApproveListPage') }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		let { noticeId, createName, inOutFlag } = this.props.navigation.state.params || {};
		console.log('this.props.navigation.state.params', this.props.navigation.state.params)
		this.createName = createName || '';
		this.noticeId = noticeId;
		this.inOutFlag = inOutFlag;
		this.state = {
			pageState: 'loading'
		};
		this.sendData = {
			noticeId
		};
	}

	async componentWillMount() {
		this._getMail();
	}


	//获取邮件
	_getMail = async () => {
		let respones = await APIService.stockGetMail({
			noticeId: this.noticeId || null,
			inOutFlag: this.inOutFlag || null,
		});
		/* respones = {
			modelName: {
				noticeNo: '111',
				bizType: '222'
			},
			groupList: [
				{ dictKey: "1", dictName: "群1", groupId: '1', groupName: "群1" },
				{ dictKey: "2", dictName: "群2", groupId: '2', groupName: "群2" },
			],
			warehouseMailGroupVOList: [
				{
					groupId: 1,
					defaultTitle: '出入库动态通知<${noticeNo}>${bizType}',
					emails: '111@.com;111@.com;111@.com;111@.com',//同步发送邮箱（逗号相隔）       String
					ccEmails: 'aaaa1@.com;aaaa2@.com;aaaa3@.com',//抄送邮箱（逗号相隔
					defaultContents: '',//邮件正文
					sendMode: '2', //发送状态   int   0:立即发送  1：等候发送
					sendTime: 5,//预期发送时间
					attachments: [],
				},
				{
					groupId: 2,
					defaultTitle: '出入库动态通知<${noticeNo}>${bizType}',
					emails: 'abc@.com;efg@.com;hij@.com',//同步发送邮箱（逗号相隔）       String
					ccEmails: '123@.com;456@.com;789@.com',//抄送邮箱（逗号相隔
					defaultContents: '邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文邮件正文',//邮件正文
					sendMode: null, //发送状态   int   0:立即发送  1：等候发送
					sendTime: null,//预期发送时间
					attachments: [],
				}
			],
			fromAddressEmail: "solid@sinochem.com",  //发件人邮箱
			preparedByAddress: "hongbo@sinochem.com",  //制单人邮箱
			fileId: '12331312',
			//fileName: 'cba'
		} */
		this._modify(respones);
		this.setState({
			pageState: 'data',
			data: respones
		})
	}

	//数据转换
	_modify = (data) => {
		data.groupList && data.groupList.map(item => {
			item.dictName = item.groupName;
			item.dictKey = item.groupId;
			return item;
		});
		//发送时间处理
		data.warehouseMailGroupVOList && data.warehouseMailGroupVOList.map((item) => {
			if (item.sendTime) {
				item.sendTime = moment().add('m', item.sendTime || 0).format("YYYY-MM-DD HH:mm");
			}
			return item;
		})
		this.sendData.fromAddressEmail = data.fromAddressEmail || null;  // 发件人
		this.sendData.preparedByAddress = data.preparedByAddress || null;  //收件人
		this.sendData.preparedByAddressShow = data.preparedByAddress || null;  //展是
		this.finalFileId = data.fileId;
		this.finalFileName = data.fileName;
	}






	//回掉
	_callBack = (calldata) => {
		let { data } = this.state || {};
		let { warehouseMailGroupVOList } = data || {};
		for (key in calldata) {
			if (key === 'groupId') {
				this.sendData = Object.assign({}, this.sendData, warehouseMailGroupVOList.filter(item => item.groupId == calldata[key])[0]);
				this.sendData.ccEmailsOldArr = this.sendData.ccEmails ? this.sendData.ccEmails.split(';') : [];
				this.sendData.emailsOldArr = this.sendData.emails ? this.sendData.emails.split(';') : [];
				this.setState({
					ls: true
				})
			}
		}
		this.sendData = Object.assign({}, this.sendData, calldata);
		console.log('this.sendData-回掉', this.sendData)
	}

	//预期发送时间 弹框
	_openTimeFn = () => {
		this.DatePicker.show();
	}

	// 
	_modefyArr = (str) => {
		if (Utils.isEmpty(str)) return [];
		return str.split(';');
	}



	//参数
	_getSend = () => {
		let params = Object.assign({}, this.sendData);
		params.ccEmails = this.sendData.ccEmails && this.sendData.ccEmails.split(';') || [];
		params.emails = this.sendData.emails && this.sendData.emails.split(';') || [];
		params.fileId = this.finalFileId;
		params.fileName = this.noticeId + '.pdf';
		params.noticeId = this.noticeId;
		//delete params.ccEmailsOldArr;
		//delete params.emailsOldArr;
		if (params.sendMode === '1') {
			delete params.sendTime;
		}
		return params;
	}

	_validate = (params) => {
		let { sendTime, sendMode, emails } = params || {};
		let currentTime = new Date().getTime();
		console.log('currentTime', currentTime)
		if (!sendMode) {
			ToastUtil.showWarning('请选择预期发送时间');
			return true;
		}
		if (emails.length < 1) {
			ToastUtil.showWarning('请填写发件人邮箱');
			return true;
		}

		if (sendMode === '2') {
			if (Utils.isEmpty(sendTime)) {
				ToastUtil.showWarning('请选择预期发送时间');
				return true;
			} else if (currentTime > new Date(sendTime).getTime()) {
				ToastUtil.showWarning('所选时间小于当前时间');
				return true;
			}
		}
		return false
	}



	_submit = async () => {
		let params = this._getSend();
		console.log('params', params)
		if (this._validate(params)) return;
		let respones = await APIService.stockPushMail(params);
		if (respones) {
			ToastUtil.showSuccess('邮件推送成功');
			this.props.navigation.navigate('StockApproveListPage');
		}
	}

	_noSend = () => {
		this.props.navigation.navigate('StockApproveListPage');
	}


	_remarkFocus = async () => {
		let y = this.isHeight - 1 / 3 * GLOBAL.SCREEN_HEIGHT;
		this.scrollview.scrollTo({ x: 0, y: y, animated: true });
	}
	_downloadLayout = (e) => {
		this.isHeight = e.nativeEvent.layout.y;
	}


	render() {
		let { pageState, data } = this.state;
		let { groupList, modelName } = data || {};
		let { groupId, preparedByAddress, preparedByAddressShow, defaultTitle, sendMode, sendTime, defaultContents, emails, emailsOldArr, ccEmails, ccEmailsOldArr } = this.sendData || {};
		return (
			<View style={styles.container}>
				<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
					{
						pageState == 'data' ? (<View style={{ flex: 1 }}>
							<ScrollView ref={(element) => this.scrollview = element} showsVerticalScrollIndicator={false} style={{ flex: 1, paddingHorizontal: 20 * scale }} >
								<Text style={styles.title} >{this.inOutFlag == "1" ? '出' : '入'}库通知审批通过，您还可以选择推送邮件</Text>
								<Text style={styles.prompt}>温馨提示：当前页面为第一次自动发送！</Text>
								<SelectCpt data={{ title: '群组名称', placeholder: '请选择群组', listData: groupList, id: 'groupId', value: groupId }} callBack={this._callBack} />
								{
									groupId ? <View>
										<TextareaCpt data={{ title: '邮件标题:', id: 'defaultTitle', value: defaultTitle, otherData: modelName }} callBack={this._callBack} />
										<EditMailCpt data={{ title: '收件邮箱：', id: 'emails', dataArr: this._modefyArr(emails), oldArr: emailsOldArr, preparedByAddress, preparedByAddressShow, createName: this.createName }} callBack={this._callBack} />
										<EditMailCpt data={{ title: '抄送邮箱：', id: 'ccEmails', dataArr: this._modefyArr(ccEmails), oldArr: ccEmailsOldArr }} callBack={this._callBack} />
										<SelectCpt data={{ title: '发送时间', listData: SENDDATA, id: 'sendMode', value: sendMode, sendTime }} callBack={this._callBack} timeOpen={this._openTimeFn} />
										<TextareaCpt onFocus={this._remarkFocus} data={{ title: '邮件填充:', multiline: true, inputStyle: { height: 80 * scale }, id: 'defaultContents', value: defaultContents }} callBack={this._callBack} />
										<View onLayout={(e) => { this._downloadLayout(e) }}>
											<AttachmentCpt finalFileId={this.finalFileId} finalFileName={this.finalFileName} />
										</View>
										<View style={styles.bottomBox}>
											<TouchableOpacity style={[styles.BtnBg, styles.BtnBgR]} onPress={this._submit}>
												<Text style={[styles.BtnText, styles.BtnTextActive]}>确认发送</Text>
											</TouchableOpacity>
											<TouchableOpacity style={styles.BtnBg} onPress={this._noSend}>
												<Text style={styles.BtnText}>暂不发送</Text>
											</TouchableOpacity>
										</View>
									</View> : null
								}
							</ScrollView>

						</View>) : <PageStatusIndex status={pageState} />
					}

					<DatePicker
						unit={['年', '月', '日']}
						startYear={2000}
						endYear={2100}
						onPickerConfirm={(timeArr) => {
							let timeStr = '';
							timeArr && timeArr.forEach((item, index) => {
								item = item.substring(0, item.length - 1);
								if (index < 2) {
									timeStr += item + '-';
								}
								else if (index == 2) {
									timeStr += item
								} else if (index == 3) {
									timeStr += " " + item
								} else if (index == 4) {
									timeStr += ":" + item;
								}
								console.log('timeStr999', timeStr)
							})
							this.sendData.sendTime = timeStr;
							this.setState({ ls: true })
						}}
						onPickerCancel={() => {
							console.log('cancel');
						}}
						ref={ref => this.DatePicker = ref} />
				</KeyboardAvoidingView>
			</View>
		)
	}
}


const styles = StyleSheet.create({
	container: {
		flex: 1,
		position: 'relative',
		backgroundColor: style.color.bgGray,
		//paddingBottom: 30 * scale
	},
	title: {
		fontSize: 16 * scale,
		color: '#000',
		paddingVertical: 15 * scale,
		marginTop: 15 * scale
	},
	prompt: {
		fontSize: 12 * scale,
		color: 'red',
		marginBottom: 10 * scale
	},
	boxs: {
		backgroundColor: '#fff',
		borderRadius: 6 * scale,
		paddingHorizontal: 15 * scale,
		paddingVertical: 10 * scale,
		marginBottom: 15 * scale
	},
	bottomBox: {
		width: '100%',
		//height: bottomP * scale,
		//position: 'absolute',
		//bottom: 0,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 35 * scale
	},

	btnBoxBig: {
		//position: 'absolute',
		bottom: 0,
		left: 0,
		width: '100%',
		//height: 80 * scale,
		backgroundColor: '#E8ECF5',
	},
	btnBox: {
		flexDirection: 'row',
		justifyContent: 'center',

	},
	BtnBg: {
		paddingHorizontal: 25 * scale,
		height: 32 * scale,
		borderRadius: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	BtnText: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
	},
	BtnBgR: {
		marginRight: 30 * scale,
		backgroundColor: style.color.themeColor,
	},
	BtnTextActive: {
		color: style.color.white
	}
})